package com.lucien.system.service.impl;

import com.lucien.common.fornt.ChatMsgFront;
import com.lucien.system.domain.ChatMessage;
import com.lucien.system.domain.ChatMessageExample;
import com.lucien.system.domain.SysGroupMessage;
import com.lucien.system.domain.SysUser;
import com.lucien.system.mapper.ChatMessageMapper;
import com.lucien.system.service.*;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author Lucien
 * @Date 2021/5/30 11:17
 * @Version 1.0
 * @Description:
 */
@Service
public class ChatMessageServiceImpl implements ChatMessageService {

    @Autowired
    private ChatMessageMapper messageMapper;

    @Autowired
    private MessageTypeService typeService;

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRelationShipService shipService;

    @Autowired
    private SysGroupMessageService groupMessageService;

    @Autowired
    private SysGroupService groupService;

    /**
     * 添加消息记录
     *
     * @param msg
     * @return
     */
    @Override
    public int insertMsg(ChatMessage msg) {
        if (messageMapper.insert(msg) != 1) {
            return -1;
        }
        return 1;
    }

    /**
     * 添加消息记录
     *
     * @param toId
     * @param content
     * @param msgType
     * @return
     */
    @Override
    public int insertMsg(int toId, String content, String msgType) {
        SysUser toUser = userService.selectByUserId(toId);
        ChatMessage chatMessage = new ChatMessage();
        SysUser loginUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        chatMessage.setFromId(loginUser.getId());
        chatMessage.setFromName(loginUser.getUsername());
        chatMessage.setFromProfile(loginUser.getUserProfile());
        chatMessage.setToId(toId);
        chatMessage.setToName(toUser.getUsername());
        chatMessage.setContent(content);
        chatMessage.setMessageTypeId(typeService.getTypeId(msgType));
        chatMessage.setCreateTime(new Date());

        if (messageMapper.insert(chatMessage) != 1) {
            return -1;
        }

        return 1;
    }

    /**
     * 获取用户之间的聊天记录详情
     *
     * @param toId
     * @param formId
     * @return
     */
    @Override
    public List<ChatMessage> msgList(Integer toId, Integer formId) {
        List<ChatMessage> result = new ArrayList<>();
        ChatMessageExample example = new ChatMessageExample();
        example.setOrderByClause("create_time asc");
        ChatMessageExample.Criteria criteria = example.createCriteria();
        criteria.andToIdEqualTo(toId);
        criteria.andFromIdEqualTo(formId);

        List<ChatMessage> messages = messageMapper.selectByExample(example);

        ChatMessageExample example1 = new ChatMessageExample();
        example.setOrderByClause("create_time asc");
        ChatMessageExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andToIdEqualTo(formId);
        criteria1.andFromIdEqualTo(toId);
        List<ChatMessage> chatMessages = messageMapper.selectByExample(example1);

        messages.addAll(chatMessages);

        for (ChatMessage message : messages) {
            ChatMessage chatMessage = messageMapper.selectByPrimaryKey(message.getId());
            result.add(chatMessage);
        }

        // 对消息时间排序 升序
        Collections.sort(result, new Comparator<ChatMessage>() {
            @Override
            public int compare(ChatMessage o1, ChatMessage o2) {
                return o1.getCreateTime().compareTo(o2.getCreateTime());
            }
        });

        return result;
    }

    /**
     * 获取用户聊天列表
     * @param userId
     * @return
     */
    @Override
    public List<ChatMsgFront> getMsgList(Integer userId) {
        List<ChatMsgFront> result = new ArrayList<>();

        List<Integer> friendsList = shipService.userFriendsList(userId);
        for (Integer friendId : friendsList) {
            ChatMessageExample example = new ChatMessageExample();
            example.setOrderByClause("create_time asc");
            ChatMessageExample.Criteria criteria = example.createCriteria();
            criteria.andFromIdEqualTo(friendId);
            criteria.andToIdEqualTo(userId);

            List<ChatMessage> messageList = messageMapper.selectByExample(example);

            ChatMessageExample example1 = new ChatMessageExample();
            example1.setOrderByClause("create_time asc");
            ChatMessageExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andFromIdEqualTo(userId);
            criteria1.andToIdEqualTo(friendId);

            List<ChatMessage> messageList1 = messageMapper.selectByExample(example1);

            messageList.addAll(messageList1);

            if (messageList.size() != 0) {
                // 对消息时间排序
                Collections.sort(messageList, new Comparator<ChatMessage>() {
                    //寻找时间就近的 降序
                    @Override
                    public int compare(ChatMessage o1, ChatMessage o2) {
                        return o2.getCreateTime().compareTo(o1.getCreateTime());
                    }
                });
                ChatMessage chatMessage = messageMapper.selectByPrimaryKey(messageList.get(0).getId());

                ChatMsgFront msgFront = init(chatMessage, friendId);

                result.add(msgFront);
            }
        }

        //群聊信息
        List<SysGroupMessage> groupMessages = groupMessageService.userGroupMsgList(userId);
        if (groupMessages.size() != 0){
            for (SysGroupMessage groupMessage : groupMessages) {
                ChatMsgFront groupFront = init(groupMessage);
                result.add(groupFront);
            }
        }

        Collections.sort(result, new Comparator<ChatMsgFront>() {
            @Override
            public int compare(ChatMsgFront o1, ChatMsgFront o2) {
                return o2.getCreateTime().compareTo(o1.getCreateTime());
            }
        });

        return result;
    }

    /**
     * 删除聊天记录
     *
     * @param friendId
     * @return
     */
    @Override
    public int delMsg(Integer friendId) {
        SysUser loginUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        Integer userId = loginUser.getId();
        ChatMessageExample example = new ChatMessageExample();
        ChatMessageExample.Criteria criteria = example.createCriteria();
        criteria.andFromIdEqualTo(userId);
        criteria.andToIdEqualTo(friendId);

        List<ChatMessage> messages = messageMapper.selectByExample(example);

        ChatMessageExample example1 = new ChatMessageExample();
        ChatMessageExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andFromIdEqualTo(friendId);
        criteria1.andToIdEqualTo(userId);

        List<ChatMessage> messages1 = messageMapper.selectByExample(example1);

        messages.addAll(messages1);

        // 删除聊天记录
        for (ChatMessage message : messages) {
            messageMapper.deleteByPrimaryKey(message.getId());
        }

        return 1;
    }

    /**
     * 删除多条聊天记录
     *
     * @param ids
     * @return
     */
    @Override
    public int delMsgById(Integer[] ids) {
        for (Integer id : ids) {
            messageMapper.deleteByPrimaryKey(id);
        }
        return 1;
    }

    /**
     * 撤回消息 超过5分钟不可撤回
     *
     * @param id
     * @return
     */
    @Override
    public int msgRecode(Integer id) {
        ChatMessage chatMessage = messageMapper.selectByPrimaryKey(id);
        Date createTime = chatMessage.getCreateTime();
        Calendar calendar = Calendar.getInstance();
        if (createTime.getTime() - calendar.getTimeInMillis() >= 50000) {
            return -1;
        } else {
            messageMapper.deleteByPrimaryKey(id);
            return 1;
        }
    }

    /**
     * 创建私聊信息
     *
     * @param message
     * @param friendId
     * @return
     */
    private ChatMsgFront init(ChatMessage message, Integer friendId) {
        ChatMsgFront msgFront = new ChatMsgFront();
        msgFront.setId(message.getId());
        msgFront.setFromId(message.getFromId());
        msgFront.setFromName(message.getFromName());
        msgFront.setFromProfile(message.getFromProfile());
        msgFront.setToId(message.getToId());
        msgFront.setToName(message.getToName());
        msgFront.setMessageTypeId(message.getMessageTypeId());
        msgFront.setCreateTime(message.getCreateTime());
        msgFront.setContent(message.getContent());

        SysUser friend = userService.selectByUserId(friendId);
        msgFront.setFriendId(friendId);
        msgFront.setFriendName(friend.getUsername());
        msgFront.setFriendAvatar(friend.getUserProfile());
        msgFront.setFriendState(friend.getUserStateId());

        msgFront.setGroupFlag(false);

        return msgFront;
    }

    /**
     * 创建群聊信息
     *
     * @param groupMessage
     * @return
     */
    private ChatMsgFront init(SysGroupMessage groupMessage) {
        String groupName = groupService.selectByGroupId(Long.valueOf(groupMessage.getGroupId())).getGroupName();
        String groupAvatar = groupService.selectByGroupId(Long.valueOf(groupMessage.getGroupId())).getAvatar();

        ChatMsgFront chatMsgFront = new ChatMsgFront();
        chatMsgFront.setId(Math.toIntExact(groupMessage.getId()));
        chatMsgFront.setFromId(groupMessage.getUserId());
        chatMsgFront.setFromName(groupMessage.getUsername());
        chatMsgFront.setFromProfile(groupMessage.getUserProfile());
        chatMsgFront.setToId(groupMessage.getGroupId());
        chatMsgFront.setToName(groupName);
        chatMsgFront.setMessageTypeId(groupMessage.getMessageTypeId());
        chatMsgFront.setCreateTime(groupMessage.getCreateTime());
        chatMsgFront.setContent(groupMessage.getContent());
        chatMsgFront.setFriendId(groupMessage.getGroupId());
        chatMsgFront.setFriendName(groupName);
        chatMsgFront.setFriendAvatar(groupAvatar);
        chatMsgFront.setFriendState(-1);
        chatMsgFront.setGroupFlag(true);

        return chatMsgFront;
    }
}
